package com.maila.xiaoaoschool.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.VolleyError;
import com.google.gson.Gson;
import com.maila.xiaoaoschool.R;
import com.maila.xiaoaoschool.api.LoginApi;
import com.maila.xiaoaoschool.entity.QQUser;
import com.maila.xiaoaoschool.net.VolleyInterface;
import com.maila.xiaoaoschool.util.Constants;
import com.maila.xiaoaoschool.util.PrefUtil;
import com.maila.xiaoaoschool.util.RegularUtils;
import com.maila.xiaoaoschool.util.StartActivityUtils;
import com.tencent.connect.UserInfo;
import com.tencent.mm.opensdk.modelmsg.SendAuth;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.tencent.tauth.UiError;
import com.zhy.autolayout.AutoLinearLayout;
import com.zhy.autolayout.AutoRelativeLayout;

import org.json.JSONException;
import org.json.JSONObject;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Administrator on 2017/10/26.
 */

public class LoginActivity extends AppCompatActivity {
    @BindView(R.id.white_return_iv)
    AutoRelativeLayout whiteReturnIv;
    @BindView(R.id.login_header)
    AutoLinearLayout loginHeader;
    @BindView(R.id.tv_zhanghao)
    TextView tvZhanghao;
    @BindView(R.id.please_enter_your_mobile_phone_et)
    EditText pleaseEnterYourMobilePhoneEt;
    @BindView(R.id.please_input_a_password)
    EditText pleaseInputAPassword;
    @BindView(R.id.all_denglu)
    AutoLinearLayout allDenglu;
    @BindView(R.id.btn_login)
    Button btnLogin;
    @BindView(R.id.register_tv)
    TextView registerTv;
    @BindView(R.id.forget_password_tv)
    TextView forgetPasswordTv;
    @BindView(R.id.login_byweixin)
    AutoLinearLayout loginByweixin;
    @BindView(R.id.login_byqq)
    AutoLinearLayout loginByqq;
    boolean pwdOK=false;
    boolean phoneOK=false;
    private IWXAPI api;

    private UserInfo userInfo;
    private Tencent mTencent;
    private String QQopenid="";
    private BaseUiListener listener = new BaseUiListener();
    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            if (msg.what == 0) {
                final JSONObject response = (JSONObject) msg.obj;
                if (response.has("nickname")) {
                    Gson gson=new Gson();
                    QQUser user=gson.fromJson(response.toString(),QQUser.class);
                    if (user!=null) {

                        Log.d("srg","userInfo:昵称："+user.getNickname()+"  性别:"+user.getGender()+"  地址："+user.getProvince()+user.getCity());
                        Log.d("srg","头像路径："+user.getFigureurl_qq_2());
                        new LoginApi(LoginActivity.this, new VolleyInterface() {
                            @Override
                            public void onSuccess(String result) {
                                try {
                                    JSONObject jsonObject=new JSONObject(result);
                                    int code=jsonObject.optInt("result");
                                    if(code==1){
                                        PrefUtil.savePref(LoginActivity.this,"key",jsonObject.optString("data"));
                                        Toast.makeText(LoginActivity.this,"登录成功",Toast.LENGTH_SHORT).show();
                                        finish();
                                    }else {
                                        Toast.makeText(LoginActivity.this, "登录失败", Toast.LENGTH_SHORT).show();
                                    }
                                } catch (JSONException e) {
                                    e.printStackTrace();
                                }
                            }

                            @Override
                            public void onError(VolleyError error) {

                            }
                        }).qqlogin(QQopenid,user.getNickname(),user.getFigureurl_qq_2());
                    }
                }
            }
        }
    };

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        ButterKnife.bind(this);
        initlistener();
        //通过WXAPIFactory工厂获取IWXApI的示例
        api = WXAPIFactory.createWXAPI(this, Constants.APP_ID_WX,true);
        //将应用的appid注册到微信
        api.registerApp(Constants.APP_ID_WX);
        mTencent = Tencent.createInstance(Constants.QQ_LOGIN_APP_ID, this.getApplicationContext());
    }

    private void initlistener() {
        pleaseEnterYourMobilePhoneEt.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if(pleaseEnterYourMobilePhoneEt.getText()!=null&& RegularUtils.isPhoneNumber(pleaseEnterYourMobilePhoneEt.getText().toString())){
                    phoneOK=true;
                }else {
                    phoneOK=false;
                }
                updataBtn();
            }
        });

        pleaseInputAPassword.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {

            }

            @Override
            public void afterTextChanged(Editable editable) {
                if(pleaseInputAPassword.getText()!=null&&pleaseInputAPassword.getText().length()>5){
                    pwdOK=true;
                }else {
                    pwdOK=false;
                }
                updataBtn();
            }


        });
    }
    private void updataBtn() {
        if(pwdOK&&phoneOK){
            btnLogin.setClickable(true);
            btnLogin.setBackgroundResource(R.drawable.bg_rd_orange);
        }else {
            btnLogin.setClickable(false);
            btnLogin.setBackgroundResource(R.drawable.bg_rd_gray);
        }

    }
    @OnClick({R.id.white_return_iv, R.id.btn_login, R.id.register_tv, R.id.forget_password_tv, R.id.login_byweixin, R.id.login_byqq})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.white_return_iv:
                finish();
                break;
            case R.id.btn_login:
                new LoginApi(this, new VolleyInterface() {
                    @Override
                    public void onSuccess(String result) {
                        try {
                            JSONObject jsonObject=new JSONObject(result);
                            int code=jsonObject.optInt("result");
                            if(code==1){
                                PrefUtil.savePref(LoginActivity.this,"key",jsonObject.optString("data"));
                                PrefUtil.savePref(LoginActivity.this,"phone",pleaseEnterYourMobilePhoneEt.getText().toString());
                                Toast.makeText(LoginActivity.this,"登录成功",Toast.LENGTH_SHORT).show();
                                finish();

                            }else {
                                Toast.makeText(LoginActivity.this, ""+jsonObject.optString("message"), Toast.LENGTH_SHORT).show();
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }

                    @Override
                    public void onError(VolleyError error) {

                    }
                }).login(pleaseEnterYourMobilePhoneEt.getText().toString(),pleaseInputAPassword.getText().toString());
                break;
            case R.id.register_tv:

                Intent intent=new Intent();
                intent.setClass(this, RegisterActivity.class);
                startActivityForResult(intent, 507);
                overridePendingTransition(0, 0);
                break;
            case R.id.forget_password_tv:
                StartActivityUtils.start(this,ForgetPwdActivity.class);
                break;
            case R.id.login_byweixin:

                SendAuth.Req req = new SendAuth.Req();
                req.scope = "snsapi_userinfo";//
//                req.scope = "snsapi_login";//提示 scope参数错误，或者没有scope权限
                req.state = "wechat_sdk_微信登录";
                api.sendReq(req);
                break;
            case R.id.login_byqq:

                if (!mTencent.isSessionValid())
                {
                    //注销登录 mTencent.logout(this);
                    mTencent.login(this, "all", listener);
                }
                break;
        }
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 507) {
            if (resultCode == RESULT_OK) {
                finish();
            }
        }}




    class BaseUiListener implements IUiListener {

        @Override
        public void onComplete(Object o) {
            Log.d("SRG","result:"+o.toString());
            try {
                JSONObject jsonObject = new JSONObject(o.toString());
                initOpenidAndToken(jsonObject);
                updateUserInfo();
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void onError(UiError e) {
            showMsg(0,"onError:code:" + e.errorCode + ", msg:"
                    + e.errorMessage + ", detail:" + e.errorDetail);
        }
        @Override
        public void onCancel() {
            showMsg(2,"onCancel");
        }
    }

    private void showMsg(int i, String onCancel) {
        Toast.makeText(this, i+""+onCancel, Toast.LENGTH_SHORT).show();
    }

    /**
     * 获取登录QQ腾讯平台的权限信息(用于访问QQ用户信息)
     * @param jsonObject
     */
    public void initOpenidAndToken(JSONObject jsonObject) {
        try {
            String token = jsonObject.getString("access_token");
            String expires = jsonObject.getString("expires_in");
            QQopenid= jsonObject.getString("openid");
            if (!TextUtils.isEmpty(token) && !TextUtils.isEmpty(expires)
                    && !TextUtils.isEmpty(QQopenid)) {
                mTencent.setAccessToken(token, expires);
                mTencent.setOpenId(QQopenid);
            }
        } catch(Exception e) {
        }
    }

    private void updateUserInfo() {
        if (mTencent != null && mTencent.isSessionValid()) {
            IUiListener listener = new IUiListener() {
                @Override
                public void onError(UiError e) {
                }
                @Override
                public void onComplete(final Object response) {
                    Message msg = new Message();
                    msg.obj = response;
                    Log.i("tag", response.toString());
                    msg.what = 0;
                    mHandler.sendMessage(msg);
                }
                @Override
                public void onCancel() {
                }
            };
            userInfo = new UserInfo(this, mTencent.getQQToken());
            userInfo.getUserInfo(listener);
        }
    }

}
